﻿@using System.Timers;
@using Timer = System.Timers.Timer;

<MContainer>
    <MProgressLinear Query Active="@_show" Value="@_value" Indeterminate="@_query"></MProgressLinear>
</MContainer>

@code {
    private bool _query;
    private bool _show = true;
    private double _value = 0;
    protected Timer Timer { get; set; }

    protected override void OnInitialized()
    {
        if (Timer == null)
        {
            Timer = new Timer
                {
                    Interval = 1000
                };
            Timer.Elapsed += Timer_Elapsed;
        }
        QueryAndIndeterminate();
    }

    private async void Timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        await InvokeAsync(() =>
        {
            if (_value == 100)
            {
                Timer.Stop();

                _show = false;
                StateHasChanged();
                Task.Run(async () =>
                {
                    await Task.Delay(2000);
                    QueryAndIndeterminate();
                });
            }
            else
            {
                _value += 25;

                StateHasChanged();
            }
        });
    }

    private void QueryAndIndeterminate()
    {
        _query = true;
        _show = true;
        _value = 0;

        InvokeAsync(StateHasChanged);

        Task.Run(async () =>
        {
            await Task.Delay(2500);

            _query = false;
            await InvokeAsync(StateHasChanged);
            Timer.Start();

        });
    }
}


